package com.zhp.dao.impl;

import com.zhp.dao.OrderDao;
import com.zhp.pojo.HOrder;
import com.zhp.utils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.math.BigInteger;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;

/**
 * @Author Lone Ranger
 */
public class OrderDaoImpl implements OrderDao {
    QueryRunner queryRunner = new QueryRunner(DbUtils.getDataSource());
    @Override
    public int getPayOrderCount(String odate, String edid, String sjdid, int yyztid) {
        //查询已付款的预约
        String sql = "select count(*) from h_order where edid = ? and odate = ? and sjdid = ? and yyztid = ?";
        Long query = null;
        try {
            query = queryRunner.query(sql, new ScalarHandler<Long>(),edid,odate,sjdid,yyztid);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return query.intValue();
    }

    @Override
    public int addOrder(HOrder hOrder) {
        String sql = "insert into h_order (oid,edid,udid,sjdid,yyztid,sickness,ghf,odate,rdate) " +
                " values (null,?,?,?,?,?,?,?,now())";
        int update = 0;
        try {
            update = queryRunner.update(sql,hOrder.getEdid(),hOrder.getUdid(),hOrder.getSjdid(),hOrder.getYyztid(),hOrder.getSickness(),hOrder.getGhf(),hOrder.getOdate());
            String sql2 = "select last_insert_id()";
            BigInteger lastId = queryRunner.query( DbUtils.getConnection(),sql2, new ScalarHandler<BigInteger>());
            hOrder.setOid(lastId.intValue());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return update;
    }

    @Override
    public int updateOrderStatus(int oid, Integer yyztid) {
        String sql = "update h_order set yyztid = ? where oid = ?";
        int result = 0;
        try {
            result = queryRunner.update(sql,yyztid,oid);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return result;
    }

    @Override
    public List<HOrder> findOrderByUdid(Integer did) {

        String sql = "select o.oid,o.yyztid,ui.drealname as ename, o.sickness,o.odate,t1.tname as sjd ,o.ghf,t2.tname as yyzt\n" +
                " from h_order o join h_userinfo ui on o.edid = ui.did\n" +
                " join h_type t1 on o.sjdid = t1.tid\n" +
                " join h_type t2 on o.yyztid = t2.tid \n" +
                " where o.udid = ?";
        List<HOrder> query = null;
        try {
            query = queryRunner.query(sql, new BeanListHandler<>(HOrder.class), did);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return query;
    }

    @Override
    public int updateOrderByType(int oid, int yyzt) {
        String sql = "update u_"
        return 0;
    }
}
